package com.lotusfall.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * SpringSecurity配置类
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)   // 开启方法细粒度的控制
public class SecurityConfig{

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
        // 用户没有权限时处理信息
        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                String header = req.getHeader("X-Requested-With");
                if("XMLHttpRequest".equals(header)){
                    // 返回JSON格式
                    resp.getWriter().println("403");
                }else{
                    req.getRequestDispatcher("/error403").forward(req,resp);
                }
            }
        });

        return http
                .authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/home/**").permitAll()
                .and().csrf().disable()
                .formLogin().loginPage("/login").permitAll()
                .loginProcessingUrl("/form")
                //.successForwardUrl("/main")
                //.defaultSuccessUrl("/main")
                .successHandler(new AndroidAuthenticationSuccessHandler())
                .failureHandler(new LocalAuthenticationFailureHandler())

                .and().logout().logoutSuccessUrl("/login").invalidateHttpSession(true) // 退出，同时清理session
                .and()
                .build();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());

    }

}
